Unique Binary Search Trees II

Given an integer n, generate all structurally unique BST‘s (binary search trees) that store values 1…n.

For example,

Given n = 3, your program should return all 5 unique BST’s shown below.

  1. 1 3 3 2 1
  2. \ / / / \ \
  3. 3 2 1 1 3 2
  4. / / \ \
  5. 2 1 2 3

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<TreeNode> generateTrees(int n) {
  12. return helper(1, n);
  13. }
  14. List<TreeNode> helper(int lo, int hi) {
  15. List<TreeNode> res = new ArrayList<>();
  16. if (lo > hi) {
  17. res.add(null);
  18. return res;
  19. }
  20. if (lo == hi) {
  21. res.add(new TreeNode(lo));
  22. return res;
  23. }
  24. for (int i = lo; i <= hi; i++) {
  25. List<TreeNode> left = helper(lo, i - 1);
  26. List<TreeNode> right = helper(i + 1, hi);
  27. for (TreeNode l : left) {
  28. for (TreeNode r : right) {
  29. TreeNode root = new TreeNode(i);
  30. root.left = l;
  31. root.right = r;
  32. res.add(root);
  33. }
  34. }
  35. }
  36. return res;
  37. }
  38. }